#include "tcpserver.h"
#include "ui_tcpserver.h"
#include<QFile>
#include<QDebug>
#include <QHostAddress>
#include<QMessageBox>
#include<QIcon>
#include <QDateTime>
#include <QTextStream>
#include<QThread>
#include<QCloseEvent>
#include<QFileDialog>
#include"exportthread.h"
TcpServer::TcpServer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TcpServer)
{
    ui->setupUi(this);
    qDebug()<<"主线程***********************："<<QThread::currentThread();
    setWindowIcon(QIcon(":/img/server.png"));
    loadConfig();
    m_tcpServer=new MyTcpServer;
    m_tcpServer->listen(QHostAddress(m_ip),m_port);
    logRecording("@@系统@@ :服务器进入监听状态...");

    ui->exportLabel->hide();
    ui->progressBar->setValue(0);
    ui->progressBar->hide();
}

TcpServer &TcpServer::getInstance()
{
    static TcpServer instance;
    return instance;
}

TcpServer::~TcpServer()
{
    qDebug()<<"TcpServer析构函数";
    if(m_tcpServer){
        m_tcpServer->close();
        delete m_tcpServer;
        m_tcpServer=nullptr;
    }
    delete ui;
}

void TcpServer::loadConfig()
{
    logRecording("@@系统@@ :加载配置文件中...");
    QFile file(":/server.config");
    if(file.open(QIODevice::ReadOnly)){
        QByteArray data=file.readAll();
        QString strData=data.toStdString().c_str();
        strData.replace("\r\n"," ");
        QStringList strList=strData.split(" ");
        QString ip=strList.at(0);
        QString port=strList.at(1);
        logRecording("@@系统@@ :配置文件加载成功！");
        m_ip=ip;
        m_port=port.toUShort();
        logRecording("@@系统@@ :服务器ip："+ip+"，服务器端口号："+port);
    }else{
        logRecording("@@系统@@ :配置文件加载失败！");
        QMessageBox::critical(this,"critical","打开配置文件失败");
    }

    file.close();
}

void TcpServer::closeEvent(QCloseEvent *event)
{
    int count=m_tcpServer->getTcpNums();
    if(count>0){
        QMessageBox::critical(this,"警告","当前还有 "+QString::number(count)+" 个tcp连接未退出,无法退出服务端");
        event->ignore();  // 阻止窗口关闭
    }else{
        event->accept();
    }
}

void TcpServer::logRecording(const QString & logMsg)
{
    // 获取当前时间并格式化
    QDateTime current = QDateTime::currentDateTime();
    QString strTime = current.toString("yyyy-MM-dd HH:mm:ss");
    QString msg=QString("[%1] "+logMsg).arg(strTime);
    ui->textEdit->append(msg);
}


//清空日志
void TcpServer::on_clearBtn_clicked()
{
    ui->textEdit->clear();
}

//导出日志
void TcpServer::on_exportBtn_clicked()
{
    QString saveFilePath = QFileDialog::getSaveFileName(this,"另存为","log.txt");
    if(saveFilePath.isEmpty())
    {
        QMessageBox::warning(this, "导出日志", "请指定导出位置！");
        return;
    }
    QString plainText = ui->textEdit->toPlainText();

    // 创建线程
    ExportThread *thread = new ExportThread(plainText, saveFilePath);

    //更新进度条
    connect(thread, &ExportThread::progressChanged, this, [=](int percent) {
        ui->progressBar->setValue(percent);
    });

    // 导出结束
    connect(thread, &ExportThread::exportFinished, this, [=](bool success) {
        if (success){
            QMessageBox::information(this, "导出日志", "日志导出成功！");
        }
        else{
            QMessageBox::warning(this, "导出日志", "日志导出失败！");
        }
        ui->exportLabel->hide();
        ui->progressBar->setValue(0);
        ui->progressBar->hide();
        thread->deleteLater();
    });

    ui->exportLabel->show();
    ui->progressBar->setValue(0);
    ui->progressBar->show();
    thread->start();
}

